package com.ziyan.service;

import com.ziyan.dao.URLDao;
import com.ziyan.entity.URLEntity;
import com.ziyan.error.ErrorCode;
import com.ziyan.error.UCException;
import com.ziyan.utils.URLUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZonedDateTime;
import java.util.Date;

/**
 * Created by ZMy on 2017/5/24.
 */
@Service
public class URLService {
    private final Logger log = LoggerFactory.getLogger(getClass());
    @Value("${ziyan.url}")
    private String BASE_URL = "http://localhost/";
    @Autowired
    private URLDao urlDao;

    public String toShortUrl(String url) {
        if(url.startsWith(BASE_URL)){
            throw new UCException(ErrorCode.invalid_params);
        }
        URLEntity urlEntity = urlDao.findByUrl(url);
        if (urlEntity == null) {
            urlEntity = new URLEntity();
            urlEntity.setUrl(url);
            urlEntity.setGmtCreate(new Date());
            urlEntity = urlDao.save(urlEntity);
            String key = URLUtil.genUrl(urlEntity.getId());

            urlEntity.setKeyWord(key);
            urlEntity.setShortUrl(BASE_URL + key);

            urlEntity = urlDao.save(urlEntity);
        }
        return urlEntity.getShortUrl();
    }

    @Transactional(readOnly = true)
    public String toNomalUrl(String url) {
        URLEntity urlEntity = urlDao.findByShortUrl(url);
        if (urlEntity == null) {
            throw new UCException(ErrorCode.short_url_not_found);
        }
        return urlEntity.getUrl();
    }

    public URLEntity findByKeyWord(String key) {
        return urlDao.findByKeyWord(key);
    }
}
